package com.ruoyi.framework.controller;


import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.function.service.BusinessLicenseService;
import com.ruoyi.function.service.FileUploadService;
import com.ruoyi.function.utility.MiniAppTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/file")
public class FileUploadController {

    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    private FileUploadService fileUploadService;
    
    @Autowired
    private MiniAppTokenService miniAppTokenService;

    @Autowired
    private BusinessLicenseService businessLicenseService;
    @Autowired
    private ServerConfig serverConfig;
    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file, 
                            @RequestParam("type") String type) {
        try {
            // 验证token
//            String token = ServletUtils.getRequest().getHeader("Authorization");
//            log.info("上传文件 - 收到token: {}", token);
//
//            if (token == null) {
//                return AjaxResult.error("未登录");
//            }
//
//            Map<String, Object> loginUser = miniAppTokenService.getLoginUser(token);
//            if (loginUser == null) {
//                return AjaxResult.error("登录已过期");
//            }
//
//            Long userId = Long.valueOf(loginUser.get("userId").toString());
//
            // 获取当前登录用户ID
            Long userId = SecurityUtils.getUserId();
            // 如果是营业执照,先进行识别
            if ("business".equals(type)) {
                try {
                    Object recognizeResult = businessLicenseService.recognizeBusinessLicense(
                        file.getInputStream(), 
                        userId
                    );
                    // 上传文件
                    String filePath = RuoYiConfig.getUploadPath();
                    // 上传并返回新文件名称
                    log.info("文件保存路径: {}", filePath);
                    String fileName = FileUploadUtils.upload(filePath, file);
                    filePath = serverConfig.getUrl()+"/prod-api" + fileName;
                    log.info("文件保存成功，路径: {}", filePath);
                    
                    return AjaxResult.success()
                            .put("url", filePath)
                            .put("recognizeResult", recognizeResult);
                } catch (Exception e) {
                    return AjaxResult.error("营业执照识别失败：" + e.getMessage());
                }
            }

            // 上传其他类型文件
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            log.info("文件保存路径: {}", filePath);
            String fileName = FileUploadUtils.upload(filePath, file);
            filePath = serverConfig.getUrl() +"/prod-api" + fileName;
            log.info("文件保存成功，路径: {}", filePath);
            return AjaxResult.success("上传成功", filePath);
            
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 批量上传文件
     */
    @PostMapping("/batchUpload")
    public AjaxResult batchUpload(@RequestParam("files") MultipartFile[] files,
                                 @RequestParam("type") String type) {
        try {
            // 验证token
            String token = ServletUtils.getRequest().getHeader("Authorization");
            log.info("批量上传文件 - 收到token: {}", token);
            
            if (token == null) {
                return AjaxResult.error("未登录");
            }
            
            Map<String, Object> loginUser = miniAppTokenService.getLoginUser(token);
            if (loginUser == null) {
                return AjaxResult.error("登录已过期");
            }
            
            Long userId = Long.valueOf(loginUser.get("userId").toString());
            
            if (files == null || files.length == 0) {
                return AjaxResult.error("请选择要上传的文件");
            }
            
            // 存储所有上传文件的URL
            List<String> fileUrls = new ArrayList<>();
            // 如果是营业执照类型，存储所有识别结果
            List<Object> recognizeResults = new ArrayList<>();
            
            for (MultipartFile file : files) {
                // 如果是营业执照,进行识别
                if ("business".equals(type)) {
                    try {
                        Object recognizeResult = businessLicenseService.recognizeBusinessLicense(
                            file.getInputStream(), 
                            userId
                        );
                        String filePath = fileUploadService.uploadFile(file, type);
                        fileUrls.add(filePath);
                        recognizeResults.add(recognizeResult);
                    } catch (Exception e) {
                        return AjaxResult.error("营业执照识别失败：" + e.getMessage());
                    }
                } else {
                    // 上传其他类型文件
                    String filePath = fileUploadService.uploadFile(file, type);
                    fileUrls.add(filePath);
                }
            }
            
            if ("business".equals(type)) {
                return AjaxResult.success()
                        .put("urls", fileUrls)
                        .put("recognizeResults", recognizeResults);
            }
            
            return AjaxResult.success("批量上传成功", fileUrls);
            
        } catch (Exception e) {
            log.error("批量上传文件失败", e);
            return AjaxResult.error("批量上传失败：" + e.getMessage());
        }
    }
} 